<template>
  <view class="panel-box">
    <view class="input-amount-wrap">
      <view>
        <view>充值金额</view>
        <view class="input-wrap">
          <text class="font-bold">￥</text>
          <input
            type="digit"
            maxlength="10"
            placeholder="请输入充值金额"
            v-model="inputObj.amount"
          />
        </view>
        <view class="item-hr"></view>
        <view class="input-item">
          <view>付款凭证</view>
          <view class="upload-box" @click="selectPicture">
            <view class="img-box">
              <image
                class="cover-img"
                :src="inputObj.fileUploadRespVO.url || imagesDefaultPath"
                mode="aspectFill"
              ></image>
              <image
                class="camera-imgs"
                :src="imagesCamera"
                mode="aspectFill"
              ></image>
              <view class="img-text text-color-common-self">{{
                inputObj.fileUploadRespVO.url ? '重新上传' : '点击上传付款凭证'
              }}</view>
            </view>
          </view>
        </view>
        <view class="item-hr"></view>
        <view class="input-item">
          <view>备注</view>
          <input
            v-model="inputObj.remark"
            :maxlength="100"
            placeholder="请输入备注信息"
          />
        </view>
      </view>
    </view>
    <view class="btn-wrap">
      <button @click="submitRecharge" :class="{ loading: isLoading }">
        提交
        <view v-if="isLoading" class="loading-icon"></view>
      </button>
    </view>
  </view>
</template>

<script>
import { topUpBalance } from '@/api/wallet.js';
import { getAccessToken } from '@/utils/auth';
import { toast } from '@/utils/common';
import config from '@/config';
export default {
  data() {
    return {
      inputObj: {
        id: '',
        amount: '',
        fileUploadRespVO: {},
        remark: ''
      },
      isLoading: false
    };
  },
  computed: {
    imagesDefaultPath() {
      return config.baseImgUrl + '/camera-bg.png';
    },
    imagesCamera() {
      if (this.$store.state.user.curTypeColor === '#409EFE') {
        return config.baseImgUrl + '/camera.png';
      }
      if (this.$store.state.user.curTypeColor === '#D22C2C') {
        return config.baseImgUrl + '/camera1.png';
      }
    }
  },
  onLoad(option) {
    this.inputObj.id = option.id;
  },
  methods: {
    selectPicture() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        mediaType: ['image'],
        success: (res) => {
          let curSize = res.tempFiles[0].size;
          if (curSize > 4 * 1024 * 1024) {
            toast('上传的图片不能超过4兆');
            return;
          }
          let quelityVal = 100;
          let initnum = 0.5 * 1024 * 1024;
          if (curSize > initnum) {
            quelityVal = Math.floor(100 / (curSize / initnum));
          }
          uni.compressImage({
            src: res.tempFilePaths[0],
            quelity: quelityVal,
            success: (resp) => {
              this.uploadFilesId(resp.tempFilePath);
            }
          });
        },
        fail(e) {
          console.log('上传化验单失败', e);
        }
      });
    },
    uploadFilesId(filepath) {
      const _ = this;
      wx.showLoading({
        title: '正在上传中...'
      });
      uni.uploadFile({
        url: config.baseUrl + '/infra/file/upload/v2',
        filePath: filepath,
        name: 'file',
        header: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + getAccessToken()
        },
        async success(res) {
          const data = JSON.parse(res?.data);
          wx.hideLoading();
          if (data.code === 0) {
            _.inputObj.fileUploadRespVO = data.data;
            toast('上传成功');
          } else {
            if (data.code === 413) {
              toast('上传图片过大，请重新上传，不要选择原图');
            } else {
              toast('上传失败，状态码:', data.code);
            }
          }
        },
        fail() {
          wx.hideLoading();
          uni.showToast({
            title: '上传失败',
            icon: 'fail'
          });
        }
      });
    },
    async submitRecharge() {
      if (this.isLoading) return;
      if (this.inputObj.amount === '' || this.inputObj.amount === undefined) {
        toast('请输入充值金额');
        return;
      }
      if (
        this.inputObj.amount == 0 ||
        !(
          /^\d+(\.\d{1,2})?$/.test(this.inputObj.amount) &&
          this.inputObj.amount < 10000000
        )
      ) {
        toast('充值金额的输入范围为0.01~9999999.99');
        return;
      }
      this.isLoading = true;
      const res = await topUpBalance(this.inputObj);
      if (res.code === 0 && res.data) {
        this.$tab.redirectTo('/packageA/pages/my-wallet/accountDetails');
        toast('充值成功');
      } else {
        this.isLoading = false;
        toast(res.msg || '接口查询失败');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.panel-box {
  height: 100vh;
  padding: 35.56rpx 17.78rpx;
  .input-amount-wrap {
    width: 100%;
    border-radius: 14.22rpx;
    background: #ffffff;
    display: flex;
    align-items: center;
    > view {
      color: #000000;
      padding: 35.56rpx;
    }
    .input-wrap {
      position: relative;
      input {
        margin-top: 40rpx;
        font-size: 70rpx;
        padding-left: 70rpx;
        height: 120rpx;
        line-height: 120rpx;
      }
      text {
        position: absolute;
        left: 0;
        font-size: 50rpx;
        bottom: 16rpx;
      }
    }
    .item-hr {
      margin: 26.67rpx 0;
      border-top: 1px solid #f1f2f5;
    }
    .input-item {
      display: flex;
      > view:first-child {
        width: 120px;
      }
    }
  }
  .btn-wrap {
    margin-top: 100rpx;
  }
}
.loading {
  position: relative;
}
.loading-icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  position: absolute;
  top: 29%;
  left: 36%;
  transform: translate(-50%, -50%);
}

.upload-box {
  margin: 17.78rpx 0 0 17.78rpx;
  .img-box {
    position: relative;
    width: 266.67rpx !important;
    height: 160rpx !important;
    .cover-img {
      width: 100%;
      height: 100%;
      position: relative;
    }
    .camera-imgs {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 40rpx;
      margin: auto;
      width: 100rpx;
      height: 100rpx;
    }
    .img-text {
      position: absolute;
      bottom: 21.33rpx;
      left: 0;
      right: 0;
      text-align: center;
      line-height: 21.33rpx;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
